﻿using AutoMapper;
using B.S.Medical.Api.Write.Application.Command.Department;
using B.S.Medical.Domain.Department;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;

namespace B.S.Medical.Api.Write.Application.Handler.Department
{
    public class DeleteDepartmentCommandHandle : IRequestHandler<DeleteDepartmentCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ManageModel> _manageRepository;
        private readonly ILogger<DeleteDepartmentCommandHandle> _logger;

        public DeleteDepartmentCommandHandle(IBaseRepository<ManageModel> manageRepository, ILogger<DeleteDepartmentCommandHandle> logger)
        {
            _manageRepository = manageRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(DeleteDepartmentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var manage = _manageRepository.GetAll().FirstOrDefault(x => x.IsDeleted == false);

            manage.IsDeleted = true;
            var r = await _manageRepository.UpdateAsync(manage);
            if (r > 0)
            {
                res.Msg = "删除科室成功!";
                res.Code = ApiEnum.Success;
                _logger.LogInformation($"删除科室{manage.DepartmentName}成功");
                res.Data = r;
            }
            else
            {
                res.Msg = "删除科室失败!";
                res.Code = ApiEnum.Fail;
                _logger.LogError($"删除改科室{manage.DepartmentName}失败");
                res.Data = r;
            }
            return await Task.FromResult(res);
        }
    }
}
